package com.tokenplus.thai.utils.analytics.util

import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import androidx.core.content.edit
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.tokenplus.thai.ProjectApplication
import com.tokenplus.thai.ProjectConfig
import java.sql.DriverManager.println

object AdvertIdUtil {

    /** sp key gaid */
    const val SP_KEY_GAID = "GAID"

    /** sp key gaid enable */
    const val SP_KEY_AD_ENABLE = "ENABLE"

    /** 初始化sp */
    private var mSp: SharedPreferences = ProjectApplication.instance.getSharedPreferences(
        ProjectConfig.product,
        Context.MODE_PRIVATE
    )

    /** 是否允许广告跟踪 */
    private var mAdEnabled: Int = 0

    /** 广告id, 每个接口中的advertId字段 */
    private var mAdId: String = ""

    init {
        mAdId = mSp.getString(SP_KEY_GAID, "") ?: ""
        mAdEnabled = mSp.getInt(SP_KEY_AD_ENABLE, 0)
    }

    /**
     * 初始化
     *
     * @param context Application
     */
    fun init(context: Application) {
        init(context) { _, _ -> }
    }

    /**
     * 初始化
     *
     * @param context Application
     * @param success 成功回调
     */
    fun init(context: Application, success: (String, Int) -> Unit) {
        if (mAdId.isBlank()) {
            Thread {
                try {
                    if (Looper.getMainLooper() != Looper.myLooper()) {
                        val advertisingIdClient = AdvertisingIdClient.getAdvertisingIdInfo(context)
                        val enable = if (advertisingIdClient.isLimitAdTrackingEnabled) 1 else 0
                        mAdId = advertisingIdClient.id ?: ""
                        mAdEnabled = enable

                        mSp.edit {
                            putInt(SP_KEY_AD_ENABLE, mAdEnabled)
                            putString(SP_KEY_GAID, mAdId)
                            commit()
                        }
                        println("mAdId=$mAdId mIsLimitAdTrackingEnabled=$mAdEnabled")

                        if (mAdId.isNotBlank()) {
                            Handler(Looper.getMainLooper()).post {
                                //回调通知
                                success.invoke(mAdId, mAdEnabled)
                            }
                        }
                    } else {
                        println("init GAID ERROR!!! Cannot call in the main thread, You must call in the other thread")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }.start()
        }
    }

    /**
     * 获取广告id
     *
     * @return 广告id
     */
    fun getAdId(): String {
        return mAdId
    }

    /**
     * 获取是否限制广告跟踪
     *
     * @return 限制状态
     */
    fun getAdEnabled(): Int {
        return mAdEnabled
    }

    /**
     * 获取安卓id
     *
     * @return 安卓id
     */
    fun getAndroidId(): String {
        val androidID = Settings.System.getString(
            ProjectApplication.instance.contentResolver,
            Settings.Secure.ANDROID_ID
        )
        if (androidID.isBlank())
            return System.currentTimeMillis().toString()

        if (androidID.contains("00000000"))
            return System.currentTimeMillis().toString()

        return androidID
    }
}